package com.loyal.mwm.handler;

import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.base.kit.GsonUtil;
import com.base.kit.TimeUtil;
import com.loyal.client.impl.RxSubscriberListener;
import com.loyal.core.helper.ViewHelper;
import com.loyal.mwm.R;
import com.loyal.mwm.base.BaseClickHandler;
import com.loyal.mwm.beans.FeedBackBean;
import com.loyal.mwm.beans.ResultBean;
import com.loyal.mwm.databinding.ActivityFeedbackBinding;
import com.loyal.mwm.libs.rxjava.RxProgressSubscriber;
import com.loyal.mwm.ui.FeedBackActivity;
import com.loyal.rx3.RxUtil;

public class FeedBackHandler extends BaseClickHandler implements RxSubscriberListener<String> {
    private final ActivityFeedbackBinding binding;

    public FeedBackHandler(FeedBackActivity activity, ActivityFeedbackBinding binding) {
        super(activity);
        this.binding = binding;
    }

    public void onClick(View view) {
        if (view.getId() == R.id.submitView) {
            String content = ViewHelper.getInputText(binding.editFeedBack);
            if (TextUtils.isEmpty(content)) {
                activity.showToast("请填写反馈内容");
                return;
            }
            String account = activity.getUsername();
            FeedBackBean backBean = new FeedBackBean(account, content, TimeUtil.getDateTime());
            RxProgressSubscriber<String> subscriber = new RxProgressSubscriber<>(activity);
            subscriber.setDialogMessage("").showProgressDialog(true).setSubscribeListener(this);
            RxUtil.rxExecute(subscriber.feedback(backBean.toString()), subscriber);
        }
        ViewHelper.hideKeyBoard(binding.editFeedBack);
    }

    @Override
    public void onResult(int what, Object tag, String result) {
        ResultBean<?> resultBean = GsonUtil.json2Bean(result, ResultBean.class);
        if (null != resultBean) {
            if (TextUtils.equals("1", resultBean.getCode())) {
                activity.showToast("感谢您的反馈");
                new Handler().postDelayed(() -> activity.finish(), 1000);
            } else activity.showDialog(resultBean.getMessage(), false);
        } else activity.showDialog("解析反馈数据失败", false);
    }

    @Override
    public void onError(int what, Object tag, Throwable e) {
        activity.showErrorDialog("", e);
    }
}
